package tk.hongbo.server

import android.os.Bundle
import android.view.SurfaceHolder
import androidx.appcompat.app.AppCompatActivity
import tk.hongbo.server.codec.Decoder
import tk.hongbo.server.databinding.ActivityServerBinding
import java.nio.ByteBuffer

const val PORT: Int = 9898

class ServerActivity : AppCompatActivity(), ServerManager.OnReceiveListener {
    private lateinit var binding: ActivityServerBinding
    private val manager = ServerManager(this)

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityServerBinding.inflate(layoutInflater)
        setContentView(binding.root)

        //surface
        binding.surfaceView.holder.addCallback(object : SurfaceHolder.Callback {
            override fun surfaceCreated(p0: SurfaceHolder) {
                Decoder.openDecode(binding.surfaceView.holder.surface)
            }

            override fun surfaceChanged(p0: SurfaceHolder, p1: Int, p2: Int, p3: Int) {

            }

            override fun surfaceDestroyed(p0: SurfaceHolder) {
            }
        })
    }

    override fun onStart() {
        super.onStart()
        manager.Start(PORT)
    }

    override fun onDestroy() {
        manager.Stop()
        super.onDestroy()
    }

    override fun receiveBitmap(byteBuffer: ByteBuffer?) {
        if (byteBuffer != null) {
            Decoder.decodeAndPlayBack(byteBuffer.array(), 0, byteBuffer.remaining())
        }
    }

    override fun log(msg: String) {
        binding.textView.text = msg
    }
}